<template>
  <div>
    <!-- <p>调单管理</p> -->
    <!-- 搜索栏 -->
    <div>
      <el-form
        :inline="true"
        :model="formInline"
        class="form-inline"
        :rules="rules"
        ref="formInline"
      >
        <el-row class="Search">
          <el-col :span="8">
            <el-form-item :label="'客户姓名'" prop="custName">
              <el-input
                v-model="formInline.custName"
                placeholder="请输入客户姓名"
                size="small"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="'证件号码'" prop="idNo">
              <el-input
                v-model="formInline.idNo"
                placeholder="请输入证件号码"
                size="small"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="'申请编号'" prop="applCde">
              <el-input
                v-model="formInline.applCde"
                placeholder="请输入申请编号"
                size="small"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="AdjustInput">
          <el-col :span="2">
            <el-form-item>
              <el-button
                type="primary"
                @click="perSearch(formInline)"
                size="mini"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="2"
            ><el-form-item>
              <el-button type="primary" @click="perReset()" size="mini"
                >重置</el-button
              >
            </el-form-item></el-col
          >
          <el-col :span="2"
            ><el-form-item>
              <el-button type="primary" @click="adjustorder()" size="mini"
                >调单</el-button
              >
            </el-form-item></el-col
          >
          <el-col :span="2"
            ><el-form-item>
              <el-button type="primary" @click="receive()" size="mini"
                >领单</el-button
              >
            </el-form-item></el-col
          >
        </el-row>
      </el-form>
    </div>
    <!-- 表单数据 -->
    <adjustmentTab
      :option="optionList"
      :tableData="tableData"
      @handleChange="handleChange"
      @receive2="receive2"
    ></adjustmentTab>

    <!-- 调单 -->
    <el-dialog title="调单" :visible.sync="showadjustorder">
      <div style="display: flex; align-items: center; margin-top: 20px">
        <p style="width: 100px">行政组:</p>
        <!-- 新 -->
        <!-- 修改调单select -->
        <avue-cascader
          :emit-path="false"
          check-strictly
          v-model="selectedDeptCodes"
          :dic="deptOptions"
          @change="handleDeptChange"
        ></avue-cascader>
      </div>

      <div style="display: flex; align-items: center; margin-top: 20px">
        <p style="width: 100px">处理人:</p>
        <!-- 新 -->
        <el-select
          filterable
          v-model="selectedUser"
          @change="handleSelectChange"
          placeholder="请选择用户"
        >
          <el-option
            v-for="user in rawUsersdata"
            :key="user.agentId"
            :label="user.nickName"
            :value="user.agentId"
          ></el-option>
        </el-select>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showadjustorder = false">取 消</el-button>
        <el-button type="primary" @click="adjustmentInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import {} from "@/api/";
import adjustmentTab from "@/views/adjustment/adjustmentTab.vue";
import {
  queryInfoCMIS200028,
  queryInfodraw,
  queryInfotd,
  getUserInfo, //内管拿行政组和座席
  getUserInfo2,
  getagentuser,
} from "@/api/hubeixiaojin/queryInfo";
// import { AvueCascader } from "avue";
export default {
  name: "adjustment",
  components: {
    adjustmentTab,
    // AvueCascader
  },

  data() {
    // 表单身份证
    var idcardReg =
      /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("证件号不能为空!!"));
      }
      if (!idcardReg.test(value)) {
        callback(new Error("请输入正确的证件号码！"));
      } else {
        callback();
      }
    };
    return {
      sqStatus: "0", //面签数据申请状态
      props: {
        label: "name",
        value: "code",
      },
      agentUser: [],
      selectedUser: "",
      form: {
        region: "",
        region2: "",
      },
      formLabelWidth: "120px",
      showadjustorder: false,
      formInline: {
        custName: "",
        idNo: "",
        applCde: "",
      },
      //客户信息
      tableData: {
        list: [],
        paging: true,
        page: {
          total: "",
          pageSize: 10,
          page: 1,
        },
      },
      //表头
      optionList: [
        {
          label: "客户申请编号",
          prop: "applCde",
        },
        {
          label: "客户证件号码",
          prop: "idNo",
        },
        {
          label: "客户名称",
          prop: "custName",
        },
        {
          label: "贷款申请金额",
          prop: "applyAmt",
        },
        {
          label: "贷款期限",
          prop: "applyTnr",
        },
        {
          label: "门店",
          prop: "cooprName",
        },
        {
          label: "申请类型", //没找到
          prop: "wfiIntoPiecesMarked",
        },
        {
          label: "进件通道",
          prop: "docChannel",
        },
        {
          label: "申请日期",
          prop: "applyDt",
        },
        {
          label: "持续时长/进件时长",
          prop: "durationShow",
        },
        {
          label: "申请状态",
          prop: "wfiStatus",
        },
        {
          label: "是否挂起",
          prop: "suspendInd",
        },
        {
          label: "办理人",
          prop: "agentName",
        },
        {
          label: "调单指定人",
          prop: "dispatchingPerson",
        },
        {
          label: "营销中心",
          prop: "marketingCenter",
        },
      ],
      receiveInfo: [], //选择的待领单数据']
      agentInfo: {
        //当前座席名字和id
        // dispatchingPerson: Constants.Agent.agentName,
        // dispatchingId: Constants.Agent.agentId,
        // //目标座席和id
        // agentId: "",
        // agentName: "",
        // //座席行政组
        // deptGroupName: Constants.Agent.deptGroupName,
        // //行政组code
        // deptGroupCode: Constants.Agent.deptGroupCode,
        // //access_token
        // access_token: Constants.Agent.access_token,
        // //tenantId
        // tenantId: Constants.Agent.tenantId,
        // //orgCode
        // orgCode: Constants.Agent.orgCode
      }, //调单用到的座席信息
      datas: [], //行政组信息
      mockData: [],
      selectedDeptCodes: [], // 保存选中的行政组层级代码
      deptOptions: [], // 存储Avue Cascader组件的数据源
      selectedUser: "", // 当前选中的用户
      selectedDeptCodes: [],
      selectedCode: "", //当前选中的行政组
      rawUsers: [], // 过滤后的用户列表
      rawUsersdata: {}, //select展示数据
      tdagentid: "",
      tdagentname: "",
    };
  },

  mounted() {
    // console.log("sessionstr==", sessionStorage.getItem("userInfo"));

    const sessionStr = sessionStorage.getItem("userInfo");
    console.log("sessionStr", sessionStr);
    const agentUser = JSON.parse(sessionStr);
    console.log("转换后的对象:", agentUser);
    if (!agentUser) {
      return;
    }
    this.agentInfo = agentUser.content;
    console.log("this.agentInfo:", this.agentInfo);

    this.getInfo(); //面签列表
    // setTimeout(() => {
    this.getAgentInfo(); //行政组信息
    // }, 1000);
  },
  // computed: {
  //   // users() {
  //   //   console.log("this.rawUsers==", this.rawUsers);
  //   //   // 返回转换后的数据，以便于el-select使用
  //   //   return this.rawUsers.map(user => ({
  //   //     ...user,
  //   //     // 确保value和label属性存在，即使它们与原始数据中的属性相同
  //   //     value: user.agentId,
  //   //     label: user.nickName
  //   //   }));
  //   // }
  // },

  methods: {
    users(data) {
      console.log("data==", data);
      // 返回转换后的数据，以便于el-select使用
      return data.map((user) => ({
        ...user,
        // 确保value和label属性存在，即使它们与原始数据中的属性相同
        value: user.agentId,
        label: user.nickName,
      }));
    },

    formatData(data) {
      // 创建一个基础的节点对象，包含 value 和 label
      const node = {
        value: data.code,
        label: data.name,
        children: [],
      };

      // 如果节点有 children 属性并且是一个非空数组，递归处理子节点
      if (
        data.children &&
        Array.isArray(data.children) &&
        data.children.length > 0
      ) {
        node.children = data.children.map((child) => this.formatData(child));
      }

      // 返回处理后的节点
      return node;
    },
    handleDeptChange(value) {
      // value 是选中项的值数组
      // 假设你只想获取最后一个选中的code，即最细粒度的行政组
      if (Array.isArray(value) && value.length > 0) {
        this.selectedDeptCode = value[value.length - 1];
        console.log("当前选中行政组:", this.selectedDeptCode);

        var params = {
          // dataType: "Agent",
          deptGroupCode: this.selectedDeptCode,
          tenantId: this.agentInfo.tenantId,
          // isQueryRelObj: true
        };
        getagentuser(params)
          .then((res) => {
            // console.log("座席信息==", res.data.data.list);

            // this.rawUsers == res.data.data.list;
            this.rawUsersdata = this.users(res.data.data.list);
          })
          .catch((err) => {
            console.log(err);
          });

        //选中行政组后，通过行政组获取座席
      } else {
        this.selectedDeptCode = "";
      }
    },

    handleSelectChange(agentId) {
      // console.log("选座席切换==", agentId);
      // console.log("保存座席信息==", this.agentInfo);
      console.log("this.rawUsersdata==", this.rawUsersdata);
      // 根据agentId找到对应的用户对象
      const selectedUser = this.rawUsersdata.find(
        (user) => user.agentId === agentId
      );

      console.log("selectedUser=", selectedUser);

      if (selectedUser) {
        // 打印agentId和nickName
        // 调单选择的座席信息
        this.tdagentid = selectedUser.agentId;
        this.tdagentname = selectedUser.nickName;
        console.log("Selected Agent ID:", selectedUser.agentId);
        console.log("Selected Nickname:", selectedUser.nickName);

        // 如果需要，也可以在这里更新其他数据或状态
      }
    },
    getInfo() {
      // console.log("获取待面签数据");
      var params = {
        page: this.tableData.page.page, //翻页当前页码
        pageSize: this.tableData.page.pageSize, //翻页一次显示数量
        sortCol: "id",
        condition: {
          status: "0,1,2,3,10",
          pushStatus: false,
          custName: this.formInline.custName, //客户姓名
          idNo: this.formInline.idNo, //身份证
          applCde: this.formInline.applCde, //申请编号
        }, //申请状态
      };

      queryInfoCMIS200028(params, this.agentInfo)
        .then((res) => {
          if (res.data.retCode === 200) {
            console.log("收到返回的调单面签信息=", res);
            this.tableData.list = res.data.data.listData; //数据
            this.tableData.page.total = res.data.data.totalCount; //总笔数
          } else {
            // console.log(res.msg);
            window.globalUiKit.notify("提示", "未查询到面签信息", "info");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    getAgentInfo() {
      // console.log(
      //   //   "调用内管获取座席信息,当前行政组==",
      //   "-----this.agentInfo ==",
      //   this.agentInfo
      // );
      //初始化树
      var params = {
        // dataType: "Agent",
        deptGroupCode: this.agentInfo.deptGroupCode,
        tenantId: this.agentInfo.tenantId,
        // isQueryRelObj: true
      };

      getUserInfo2(params)
        .then((res) => {
          if (res.data.code === 200) {
            this.deptOptions = [this.formatData(res.data.data[0])];
          }
          // console.log("行政组信息==", res.data.data[0]);
          //模拟数据
          // this.datas = [...res.data.data[0]];
          // this.deptOptions = this.formatData(res.data.data[0]);
        })
        .catch((err) => {
          console.log(err);
        });
    },

    adjustmentInfo() {
      // console.log("确定按钮", this.selectedUser);
      this.showadjustorder = false;
      var arr = [];

      this.receiveInfo.forEach((element) => {
        arr.push(element.id);
      });
      //调单数据
      var params = {
        condition: {
          //操作人,当前座席
          dispatchingPerson: this.agentInfo.agentName,
          //选中人,目标座席
          agentId: this.tdagentid,
          agentName: this.tdagentname,
        },
        ids: arr,
        sortCol: "id",
      };

      queryInfotd(params, this.agentInfo)
        .then((res) => {
          if (res.data.retCode === 200) {
            // console.log("返回调单结果=", res);
            this.$message.success("调单成功");
            this.getInfo();
          } else {
            window.globalUiKit.notify("提示", "调单失败", "info");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    perSearch(val) {
      // console.log("查询", val);
      this.tableData.page.page = 1;
      this.getInfo();
    },
    perReset() {
      this.formInline = {
        custName: "",
        idNo: "",
        applCde: "",
      };
    },
    adjustorder(val) {
      //展开弹窗，下拉框选项
      //在这里获取数据后展开或者页面初始化获取，这里直接展开

      this.showadjustorder = true;
    },
    receive() {
      // console.log("领单=", this.agentInfo);
      if (this.receiveInfo.length > 1) {
        return this.$message.error("领单每次只能勾选一条数据");
      }
      var params = {
        condition: {
          dispatchingPerson: this.agentInfo.agentName,
          agentId: this.agentInfo.agentId,
          agentName: this.agentInfo.agentName,
        },
        ids: [this.receiveInfo[0].id],
        sortCol: "id",
      };

      queryInfodraw(params, this.agentInfo)
        .then((res) => {
          console.log(res);
          if (res.data.retCode === 200) {
            if (res.data.data.errorCode == "10002") {
              return this.$message.error(res.data.data.errorMess);
            }
            this.$message.success("领单成功");
            this.getInfo();
          } else {
            this.$message.error("领单失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    receive2(val) {
      this.receiveInfo = val;
      // console.log("勾选点击数据", val);
    },
    handleChange(newPage) {
      // console.log("NewPage==", newPage);
      this.tableData.page.page = newPage;
      // var params = {
      //   turnPageBeginPos: newPage, //翻页当前页码
      //   turnPageShowNum: this.tableData.page.pageSize //翻页一次显示数量
      // };
      // console.log("this.tableData.page.page==", this.tableData.page.page);
      this.getInfo();
    },
  },
};
</script>

<style>
.form-inline {
  /* display: flex; */
  /* justify-content: space-between; */
  /* margin-bottom: 20px; */
}
.Search {
  width: 100%;
  text-align: center;
}
.AdjustInput {
  display: flex;
  justify-content: end;
}
</style>
